package cn.nexttec.noteplayer.ui.adapters

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import cn.nexttec.noteplayer.R
import cn.nexttec.noteplayer.common.TAG
import cn.nexttec.noteplayer.common.debug
import cn.nexttec.noteplayer.common.gson
import cn.nexttec.noteplayer.databinding.ItemVideoFileBinding
import cn.nexttec.noteplayer.databinding.ItemVideoHeaderBinding
import cn.nexttec.noteplayer.models.VideoFileInfo
import com.bumptech.glide.Glide

class VideoFileAdapter : RecyclerView.Adapter<VideoFileAdapter.ViewHolder>() {
    private var files = ArrayList<VideoFileInfo>()
    var onItemClick: ((VideoFileInfo) -> Unit)? = null
    var onItemLongClick: ((VideoFileInfo) -> Unit)? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        return VideoViewHolder(
            ItemVideoFileBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        )
    }

    override fun getItemCount(): Int = files.size



    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

            val videoFile = files[position]
            val videoHolder = holder as VideoViewHolder
            videoHolder.setVideoFile(videoFile)
            videoHolder.binding.root.setOnClickListener {
                onItemClick?.invoke(videoFile)
            }
            videoHolder.binding.root.setOnLongClickListener {
                onItemLongClick?.invoke(videoFile)
                true
            }
    }

    fun setVideoFiles(fileInfos: List<VideoFileInfo>, showHeader: Boolean) {
        this.files.clear()
        fileInfos.forEach {
            TAG debug "${if (it.isVideoFile) "\uD83D\uDCFC" else "\uD83D\uDCC1"} ${it.name}, ${it.gson()}"
        }
        this.files.addAll(fileInfos) // ✅ 不要加空的 VideoFileInfo()
        notifyDataSetChanged()
    }

    fun clear() {
        this.files.clear()
        notifyDataSetChanged()
    }

    open inner class ViewHolder(val itemView: View) : RecyclerView.ViewHolder(itemView) {

    }

    inner class VideoViewHolder(val binding: ItemVideoFileBinding) : ViewHolder(binding.root) {
        fun setVideoFile(videoFileInfo: VideoFileInfo) {
            if (!videoFileInfo.isVideoFile) {
                binding.ivType.setImageResource(R.drawable.folder)
            } else {
                try {
                    Glide.with(binding.root)
                        .load(videoFileInfo!!.path)
                        .frame(0)
                        .into(binding.ivType)
                } catch (e: Exception) {
                    binding.ivType.setImageResource(R.drawable.movie)
                }
            }
            binding.tvName.setText(videoFileInfo.name)
            binding.tvTip.setText(videoFileInfo.tip)
        }

    }

    inner class Header(val binding: ItemVideoHeaderBinding) : ViewHolder(binding.root)
}